package com.sora.sora.job.excutor.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sora.sora.common.mapper.ArticleMapper;
import com.sora.sora.common.model.entity.ArticleEntity;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.log4j.Log4j2;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

@Log4j2
@Component
public class ArticleJob {

    @Resource
    ArticleMapper articleMapper;

    @Resource
    RedisTemplate<String, String> redisStringTemplate;

    @Resource
    RedisTemplate<String, Object> redisObjectTemplate;

    @Resource
    ObjectMapper objectMapper;


    @XxlJob("synchronizeArticle")
    public void synchronizeArticle() {
        XxlJobHelper.log("<<<<<<<< 同步文章 >>>>>>>>");
        List<Object> unSyncedId = redisObjectTemplate.opsForList().range("pageSync", 0, -1);
        List<Object> failure = new LinkedList<>();
        ArticleEntity articleEntity;
        int view;
        int like;
        int collection;
//        for (Object article : unSyncedId) {
        for (int i = 0; i < unSyncedId.size(); i++) {
            int id = Integer.parseInt(unSyncedId.get(i).toString());
//            String data = redisStringTemplate.opsForValue().get("pageObject:" + id);
//            ArticleParam param = null;
//            try {
//                param = objectMapper.readValue(data, ArticleParam.class);
//            } catch (JsonProcessingException e) {
//                e.printStackTrace();
//                log.error("执行同步任务时反序列化出错", e);
//            }
            view = (Integer) redisObjectTemplate.opsForHash().get("pageObject", "view:" + id);
            like = (Integer) redisObjectTemplate.opsForHash().get("pageObject", "like:" + id);
            collection = (Integer) redisObjectTemplate.opsForHash().get("pageObject", "collection:" + id);
            int result = articleMapper.updateApperance(id, view, like, collection);
            if (result <= 0) {
                failure.add(result);
                XxlJobHelper.log("<<<<<<<< id为" + id + "的文章同步失败 >>>>>>>>>");
            }
        }
    }
}
